package email

import (
	"fmt"
	"log"
	"net/http"
	"net/smtp"
	"os"
	"sync"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/jordan-wright/email"
)

func initEmailServer() *email.Pool {
	p, err := email.NewPool(
		"smtp.qq.com:25",
		1,
		smtp.PlainAuth(emailSettings.Identity, emailSettings.Username, emailSettings.Password, emailSettings.Hostname),
	)

	if err != nil {
		log.Fatal("failed to create pool:", err)
	}
	return p
}

type Email interface {
	Send()
	Receive()
}

type Message struct {
	From    string
	To      string
	Subject string
	Body    string
}

func (m *Message) Send() {
	p := initEmailServer()

	var wg sync.WaitGroup

	ch := make(chan *email.Email, 10)
	for i := 0; i < 2; i++ {
		go func() {
			defer wg.Done()
			for e := range ch {
				err := p.Send(e, 10*time.Second)
				if err != nil {
					_, _ = fmt.Fprintf(os.Stderr, "email:%v sent error:%v\n", e, err)
				}
			}
		}()
	}
	for i := 0; i < 2; i++ {
		wg.Add(1)
		e := email.NewEmail()
		e.From = "705301804@qq.com"
		e.To = []string{"705301804@qq.com"}
		e.Subject = "Awesome web"
		e.Text = []byte(fmt.Sprintf("Awesome Web %d", i+1))
		ch <- e
	}

	println("发送邮件")
	println(m.From)
	println(m.To)
	println(m.Subject)
	println(m.Body)
}

func (m *Message) Receive() {
	println("接收邮件")
	println(m.From)
	println(m.To)
	println(m.Subject)
	println(m.Body)
}

func SendMessage(c *gin.Context) {
	message := Message{
		From:    "1",
		To:      "2",
		Subject: "hello",
		Body:    "world",
	}
	message.Send()
	c.JSON(http.StatusOK, gin.H{"message": message})
}
